﻿using BaseUtils.Logger;
using DeviceManage.PLC;
using DriveManage.SocketClient;
using Newtonsoft.Json;
using Service.src.Flow.Server;
using Service.src.NW.Model;
using Service.src.NW.Model.Enum;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace Service.src.NW.Processor.Core
{
    public class EventProcessor : BaseProcessor
    {

        //static ISocketServerManager socketServer = null;

        /// <summary>
        /// 监听事件
        /// </summary>
        public static void OnEvent()
        {

            // 流程监听
            if (AppData.AllEvents?.Any() == true)
            {
                AppData.AllEvents.ForEach(e =>
                {
                    _ = Task.Run(() =>
                    {
                        try
                        {
                            NewMethod(e);
                        }
                        catch (Exception ex)
                        {
                            LoggerService.Error($"事件监听出错，事件ID：{e.Id},原因："+ex.Message, ex);
                        }
                    });
                });
            }
        }

        public static object lockObject = new object();

        private static void NewMethod(SystemEvent SE)
        {
            while (AppData.AppRunSuccess)
            {
                int tid = SE.TriggerSourceId;

                if (AppData.IPLCHelpers.ContainsKey(tid))
                {
                    IPLCHelper PLC = AppData.IPLCHelpers[tid];
                    if (PLC.LinkSucceed)
                    {
                        if (!AppData.CachePLCAddressList.ContainsKey(SE.TriggerId))
                        {
                            throw new Exception($"通过PLC触发事件错误，触发的地址ID：{SE?.TriggerId},请检查对应PLC下是否有这个地址ID，解决方案：1，重新添加一个地址，2，重启软件读取配置");
                        }
                        var s = PLC.Read(AppData.CachePLCAddressList[SE.TriggerId].Address);
                        string Message = s.ToString();
                        if (!string.IsNullOrEmpty(Message))
                        {
                            TriggerFlow(SE, null, Message);
                        }
                    }
                }

                if (AppData.SocketHandlers.ContainsKey(tid))
                {
                    ISocketHandler socket = AppData.SocketHandlers[tid];
                    if (socket.Terminal == "client")
                    {
                        socket.OnReceiveMsg += (scm, Message) => OnClient(SE, scm, Message);
                    }
                    if (socket.Terminal == "server")
                    {
                        socket.OnMessageReceived += (ServerManager, scm, buffer, Message) => OnServer(SE, scm, Message);
                    }
                }
                Thread.Sleep(1000);
            }
        }

        private static void OnServer(SystemEvent e, TcpClient scm, string Message)
        {
            TriggerFlow(e, "server", Message);
        }

        private static void OnClient(SystemEvent e, SocketClientManager scm, string Message)
        {
            TriggerFlow(e, "client", Message);
        }

        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="SE"></param>
        /// <param name="scm"></param>
        /// <param name="Message"></param>
        private static void TriggerFlow(SystemEvent SE, string Terminal, string Message)
        {
            string TriggerValue = SE.TriggerValue;
            if (Terminal != null)
            {
                 TriggerValue = JsonConvert.DeserializeObject<string>($"\"{SE.TriggerValue}\"");
            }
            switch (SE.TriggerMode)
            {
                case TriggerModeEnum.VALUE_EQUAL:
                    if (Message == TriggerValue)
                    {
                        LoggerService.Info($"流程被触发，触发模式 = VALUE_EQUAL；流程ID：{SE.Id},{SE.TriggerFlow}");
                        FlowServer.RunFlow(SE.TriggerFlow);
                    }
                    break;
                case TriggerModeEnum.VALUE_CONTAINS:
                    if (Message.Contains(TriggerValue))
                    {
                        LoggerService.Info($"流程被触发，触发模式 = VALUE_CONTAINS；流程ID：{SE.Id},{SE.TriggerFlow}");
                        FlowServer.RunFlow(SE.TriggerFlow);
                    }
                    break;
                case TriggerModeEnum.VALUE_NOT_EQUAL:
                    if (Message != TriggerValue)
                    {
                        LoggerService.Info($"流程被触发，触发模式 = VALUE_NOT_EQUAL；流程ID：{SE.Id},{SE.TriggerFlow}");
                        FlowServer.RunFlow(SE.TriggerFlow);
                    }
                    break;
                case TriggerModeEnum.VALUE_CHANGE:
                    if (Message != SE.BeforeTriggerValue)
                    {
                        SE.BeforeTriggerValue = Message;
                        LoggerService.Info($"流程被触发，触发模式 = VALUE_CHANGE；流程ID：{SE.Id},{SE.TriggerFlow}");
                        FlowServer.RunFlow(SE.TriggerFlow);
                    }
                    break;
            }
        }
    }
}
